<?php if (!defined("QCMS")){die("Direct script access not allowed.");}
/* SQLite database interface for QuickCMS */

class SQLiteDB implements DB {
	var $filename;
	var $db;
	var $insertId = false;
	var $errors = true;
	
	// Active Record
	var $sql;
	var $type = false;
	var $cols=array();
	var $table = false;
	var $where = false;
	var $values = false;
	
	function __construct($file=false)
	{
		if($file==false)
		{
			$this->error("Please specify a filename when calling the SQLiteDB class.");
		}
		else
		{
			$this->filename = $file;
			try
			{
				$this->db = new SQLiteDatabase($this->filename);
			}
			catch(exception $e)
			{
				$this->error(
					"There was an error initializing the SQLite database. It is most likely the directory/file specified in the config is not writeable.",
					true
				);
			}
		}
	}
	
	/* Main Opperations */
	
	
	function insert($table=false)
	{
		$this->type = "INSERT";
		if($table !== false){$this->table = $table;}
		return $this;
	}
	
	function select($cols="*")
	{
		if ( $this->type !== false )
		{
			$this->error("Invalid use of select, query type already defined. Did you forget to ->flush?");
			return $this;
		}
		if (is_array($cols))
		{
			if($cols=="*"){$this->cols[] = "*";}
			else{$this->cols = $cols;}
		}
		else
		{
			$c = explode(",",$cols);
			foreach ( $c as $d )
			{
				$d = trim($d);
				if ( $d != "" ) { $this->cols[] = $d; }
			}
		}
		$this->type = "SELECT";
		return $this;
	}
	
	function update($table=false)
	{
		$this->type = "UPDATE";
		if($table !== false){$this->table = $table;}
		return $this;
	}
	function create($table=false)
	{
		$this->type = "CREATE";
		if($table !== false){$this->table = $table;}
		return $this;
	}
	function columns($cols=false)
	{
		if($cols !== false)
		{
			$this->cols = $cols;
		}
		return $this;
	}
	
	
	/* Function: where
	 * Specify conditions for select and update statements.
	 */
	function where($conditions=false)
	{
		foreach ( $conditions as $col => $value )
		{
			$this->where[$col] = $value;
		}
		return $this;
	}
	
	function values($values=array())
	{
		foreach ($values as $column => $value)
		{
			$this->values[$column] = $value;
		}
		return $this;
	}
	
	function limit()
	{
		return $this;
	}
	
	/* Function: table
	 * Specifies the table to be opperated on.
	 */
	function table($table=false)
	{
		if($table !== false)
		{
			$this->table = $table;
		}
		else
		{
			$this->error("Error, table name parameter is required for table method.");
		}
		return $this;
	}
	
	/* Function: from
	 * Alias of table
	 */
	function from($table)
	{
		return $this->table($table);
	}
	
	/* Function: into
	 * Alias of table
	 */
	function into($table)
	{
		return $this->table($table);
	}
	
	function errors($on=true)
	{
		$this->errors = $on;
		return $this;
	}
	

	function exec()
	{
		$this->compile();
		$this->sql($this->sql);
		$this->flush();
		return $this;
	}
	function get()
	{
		$this->compile();
		$r = $this->queryArray($this->sql);
		$this->flush();
		return $r;
	}
	function getSql()
	{
		$this->compile();
		$r = $this->sql;
		$this->flush();
		return $r;
	}
	function group()
	{
		$this->compile();
		$s = $this->sql;
		$this->flush();
		$this->sql = $s;
		return $this;
	}
	
	
	private function compile()
	{
		if ( $this->type == "INSERT" )
		{
			$this->sql .= "INSERT INTO '".$this->table."' ";
			$vals = true;
		}
		if ( $this->type == "SELECT" )
		{
			$this->sql .= "SELECT ";
			$cols = true;
			$from = true;
		}
		if ( $this->type == "UPDATE" )
		{
			$this->sql .= "UPDATE '".$this->table."' ";
			$set = true;
		}
		if ( $this->type == "CREATE" )
		{
			$this->sql .= "CREATE TABLE '".$this->table."' ";
			$create = true;
		}
		if ($cols)
		{
			$i = 0;
			foreach ( $this->cols as $col )
			{
				if($i==0){$i++;}else{$this->sql .= ", ";}
				$this->sql .= $col;
			}
			$this->sql .= " ";
		}
		if($create)
		{
			$this->sql .= "(";
			$i = 0;
			foreach ($this->cols as $col => $opts )
			{
				if($i==0){$i++;}else{$this->sql .= ", ";}
				$this->sql .= "'".$col."'";
				foreach ( $opts as $opt )
				{
					$this->sql .= " ".$opt."";
				}
			}
			$this->sql .= ")";
		}
		if ( $this->table !== false && $from === true)
		{
			$this->sql .= "FROM '".$this->table."'";
		}
		if ( $this->values !== false && $set && !$vals )
		{
			$this->sql .= "SET ";
			$i = 0;
			foreach ( $this->values as $col => $value )
			{
				if($i==0){$i++;}
				else{$this->sql .= ", ";}
				$this->sql .= "".$col."='".$value."'";
			}
		}
		if ( $this->values !== false && $vals && !$set )
		{
			$a = "(";
			$b = " VALUES (";
			$i = 0;
			foreach ( $this->values as $col => $value )
			{
				if($i==0){$i++;}
				else{$a .= ", ";$b .= ", ";}
				$a .= "'".$col."'";
				$b .= "'".$value."'";
			}
			$this->sql .= $a.") ".$b.")";
		}
		if ( $this->where !== false )
		{
			$this->sql .= " WHERE ";
			$i = 0;
			foreach ( $this->where as $col => $value )
			{
				if($i==0){$i++;}
				else{$this->sql .= ", ";}
				$this->sql .= "".$col."='".$value."'";
			}
		}
		$this->sql .= ";";
		$cols = false;
		$vals = false;
		$from = false;
		$create = false;
		$i = false;
	}
	
	
	private function flush()
	{
		$this->sql = "";
		$this->type = false;
		$this->cols = array();
		$this->from = false;
		$this->where = false;
		$this->errors = true;
		return $this;
	}
	
	
	/* Function: install
	 * This method initialises the database.
	 * If the database is already found & is initialised this should error.
	 */
	function install()
	{
		$this->create("libraries")->columns(
			array(
				'id' => array("INTEGER","PRIMARY KEY"),
				'name' => array("CHAR(255)","UNIQUE"),
				'enabled' => array("INT")
			)
		)->exec();
		/*$this->sql(
			"CREATE TABLE 'libraries' ('id' INTEGER PRIMARY KEY, 'name' CHAR(255) UNIQUE, 'enabled' INT);"
		);*/
	}
	
	
	/* Function: sql
	 * Executes an sql query on the database, does NOT return any data.
	 * WARNING: there is NO data sanitation.
	 */
	function sql($sql)
	{
		$q = @$this->db->queryExec($sql);
		if ( $this->errors !== false )
		{
			if (!$q)
			{
				$this->error("DB Error: ".sqlite_error_string($this->db->lastError()));
			}
		}
	}
	
	/* Function: queryArray
	 * Executes an sql query an returns the results as an array:
	 * Array(
	 * 	[0] => Array (
	 *				col1 => value
	 *				col2 => value
	 *			)
	 *	[1] => Array ( ... )
	 *	...
	 * )
	 */
	function queryArray($sql)
	{
		$q = @$this->db->arrayQuery($sql);
		if ( $this->errors !== false )
		{
			if (!$q && $this->db->lastError() != 0)
			{
				$this->error("DB Error (".$this->db->lastError()."): ".sqlite_error_string($this->db->lastError()));
			}
		}
		return $q;
	}
	
	function insertId()
	{
		return $this->db->lastInsertRowid();
	}
	
	function affectedRows()
	{
		return $this->db->changes();
	}
	
	function lastError()
	{
		return $this->db->lastError();
	}
	
	function error($msg,$die=false)
	{
		error($msg,$die);
	}
}
?>